package com.ly.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ly.mapper.ArticleMapper;
import com.ly.pojo.Article;
import com.ly.service.ArticleService;
import com.ly.utils.PageBean;
import com.ly.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Override
    public void add(Article article) {
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        //拿已登录ID
        Map<String,Object> map= ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        article.setCreateUser(userId);
        articleMapper.add(article);
    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer category, String state) {
        //1,创建pageBean对象
        PageBean<Article> pb = new PageBean<>();
        //2,开启分页查询 pageHelper
        PageHelper.startPage(pageNum, pageSize);
        //3,调用mapper的方法
        Map<String,Object> map= ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Article> as= articleMapper.list(userId, category,state);
        //page中提供了方法，可以获得PageHelper分页查询后 得到的总记录条数和当前数据
        Page<Article> p=(Page<Article>) as;
        //把数据填到PageBean对象中
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }
}
